import * as React from 'react';
import { Route, RouteComponentProps, Redirect, Switch } from 'react-router';
import './Main.less';
import { NavLink } from 'react-router-dom';
import { observer, inject } from 'mobx-react';
import RightContent from '../rightContent/RightContent';
import ChartMessage from '../chart/ChartMessage';
import MySetting from '../my/MySetting';
import GroupView from '../group/Group';
import { MainStore, detailType } from '../../../src/store/MainStore';
import systemStore, { SystemStore } from '../../store/SystemStore';
import { RouterStore } from '../../../src/store/RouterStore';
import { autorun, IReactionDisposer } from 'mobx';

import Input from 'antd/es/input';
import Alert from 'antd/es/alert';
import Tooltip from 'antd/es/tooltip';
import Badge from 'antd/es/badge';
import Buttons from 'antd/es/button';

// import Avatar from 'antd/es/avatar';
import Modal from 'antd/es/modal';
import Icon from 'antd/es/icon';

import { Button } from 'antd/lib/radio';
import { UserAdd } from '../../interface/IaddFriend';
import { FriendStore } from '../../store/FriendStore';
import { LoginStore } from '../../store/LoginStore';
import { CreateGroupStore } from '../../store/CreatGroupStore';
import UserInfomodal from '../../component/UserInfoModal/UserInfoModal';
import { tr } from '../../i18n/tr';
import { RequestStore } from '../../store/RequestStore';
import webIM from '../../net/WebIM';
import { AvatorWithPhoto } from '../../component/avatorWithPhoto/AvatorWithPhoto';
import Popover from 'antd/es/popover';
import { Title } from '../title/Title';
import { ChatStore } from '../../store/ChatStore';
// import ipcRender from '../../ipcRender';
import xmppSdk from '../../net/XmppSDK';
import Spin from 'antd/es/spin';
import { ServerLineSelectModal } from '../../component/serverLineSelectModal/ServerLineSelectModal';
import Search from '../search/Search';
import SvgIcon from '../../component/svgIcon/SvgIcon';
import TeamView from '../team/Team';
import MesGroupSend from '../settingDetail/MesGroupSend';
import { debug } from 'console';
import MyInfoSimple from '../settingDetail/MyInfoSimple';
import { set } from 'js-cookie';
import MyInfo from '../settingDetail/MyInfo';
import ResizeBar from '../../component/resizeBar/ResizeBar';
import env from '../../utils/env'
import UserSearch from '../../component/UserSearch/UserSearch';

//import { isH5 } from '../../config/web.config';
// import { Update } from '../update/Update';



export interface IMainProps extends RouteComponentProps { }



interface WithStore extends IMainProps {
	mainStore: MainStore;
	routerStore: RouterStore;
	systemStore: SystemStore;
	friendStore: FriendStore;
	createGroupStore: CreateGroupStore;
	requestStore: RequestStore;
	chatStore: ChatStore;
	loginStore:LoginStore
}
interface IMainState {
	keyword: string;
	xmppStatus: number;
	menuShow: boolean;
	showServerLineModal: boolean;
	isW3:boolean;
	showMyInfo:boolean,
	/** 是否正在群发 */
	sendingTransmit:boolean,

}
@inject('mainStore', 'systemStore', 'routerStore', 'friendStore', 'createGroupStore', 'requestStore', 'chatStore','loginStore')
@observer
export default class Main extends React.Component<IMainProps, IMainState> {
	constructor(props: IMainProps) {
		super(props);
		(this.props as WithStore).routerStore.setHistory(this.props.history);
		this.state = {
			keyword: '',
			xmppStatus: 0,
			menuShow: false,
			showServerLineModal: false,
			isW3:false,
			showMyInfo:false,
			sendingTransmit:false,

		};
		this.injected.mainStore.showSettings(false)
		this.refMessages = React.createRef()
		this.refLeftList = React.createRef<any>()
	}
	refLeftList = React.createRef<any>()

	refMessages = React.createRef();
	get injected() {
		return this.props as WithStore;
	}

	goChatTest = ()=>{
		this.props.history.push('/main/chat');
		return;
	}
	goMyInfo = ()=>{
		
		this.setState({
			showMyInfo:true	
		})
	}
	goMy = ()=>{
		this.setState({
			isW3:false
		})
		this.injected.mainStore.filterTxt = '';
		this.injected.mainStore.clickClear = false;
		this.injected.mainStore.changeShowDetailType(detailType.my);
		this.injected.mainStore.changeTabName('my');
	}
	goTeam = ()=>{
		this.injected.mainStore.changeShowDetailType(detailType.team);
		this.injected.mainStore.changeTabName('team');
	}
	goSendMessages = ()=>{
		//this.injected.mainStore.changeShowDetailType(detailType.messages)
		//this.injected.mainStore.changeTabName('messages');
		this.injected.mainStore.showSendMessagesModel(true)
	}
	goSetting = () => {
		this.showSettings();
		// this.props.history.push('/main/settings');
		// this.setState({
		// 	isW3:false
		// })
		// this.injected.mainStore.filterTxt = '';
		// this.injected.mainStore.clickClear = false;
		// this.injected.mainStore.changeShowDetailType(detailType.setting);
		// this.injected.mainStore.changeTabName('settings');
	};

	go3w = () => {
		this.setState({
			isW3:true
		})
		this.injected.mainStore.filterTxt = '';
		this.injected.mainStore.clickClear = false;
		this.injected.mainStore.changeShowDetailType(detailType.w3);
		this.injected.mainStore.changeTabName("w3");
	}
	goChart = (name:string="chat") => {
		this.setState({
			isW3:false
		})
		this.injected.mainStore.filterTxt = '';
		this.injected.mainStore.clickClear = false;
		this.injected.mainStore.changeShowDetailType(detailType.message);
		this.injected.mainStore.changeTabName(name);
	};
	dispose: IReactionDisposer;
	componentDidMount() {
		this.dispose = autorun(() => {
			if (!this.injected.systemStore.access_token) {
				this.props.history.push('/login');
			}

			this.setState({ xmppStatus: this.injected.systemStore.xmppStatus });
			
			
		});
		
	}

	// shouldComponentUpdate(){
	//     return false;
	// }
	handleSendType = () => {
		this.setState({
			menuShow: !this.state.menuShow
		});
	};
	showInfo() {
		this.setState({
			menuShow: true
		});
	}
	componentWillUnmount() {
		this.dispose && this.dispose();
	}
	addFriend = (user: UserAdd) => {
		this.injected.mainStore.showAddFriendApply(user);
	};
	handleMobileChange = (event: any) => {
		this.setState({ keyword: event.target.value });
	};
	applyAddFriend = () => {
		this.injected.mainStore.applyAddfriend('');
		this.injected.mainStore.closeAddFriendApply()
		this.injected.mainStore.closeAddFriModal();
	};

	getXmppStatus = () => {
		/** xmpp 链接状态 0 未开始连接 1 连接中 2 连接成功 -1 初始状态 3 连接断开 */
		const antIcon = <Icon type="sync" style={{ fontSize: 14 }} spin />;
		
		if (this.state.xmppStatus == -1) {
			return (
				<span
					className='netstatus'
				// onClick={() => {
				// 	xmppSdk.selfExit = true;
				// 	webIM.loginIM();
				// }}
				>
					<Alert message="正在连接，拉取数据" type="info" />
				</span>
			);
		}
		if (this.state.xmppStatus == 1) {
			return (
				<span style={{ zIndex: 1 }} className='netstatus'>
					<Spin style={{ top: 2, left: 2 }} indicator={antIcon}>
						<Alert message="正在连接服务器" type="warning" />
					</Spin>
				</span>
			);
		} else if (this.state.xmppStatus == 2) {
			return null;
		} else {
			return (
				<span
					className='netstatus'
					onClick={() => {
						xmppSdk.selfExit = true;
						webIM.loginIM();
					}}
				>
					<Alert message="网络状态不良,请检查网络" type="error" />
				</span>
			);
		}
	};
	goCreateGroup = () => {
		
		this.injected.mainStore.changeShowDetailType(detailType.CrtGroup);
		this.injected.createGroupStore.init();
	};
	getUnreadCount =()=>{
		return this.injected.chatStore.unReadMsgsCount
	}

	handleChange(value: any) {
		console.log(`selected ${value}`);
	}

	loginOut = () => {
		// systemStore.access_token = '';
		this.injected.loginStore.logout()
		this.injected.systemStore.loginOut()
		this.injected.chatStore.loginOut()
		webIM.logout(true);
	};
	showServerLineModal = () => {
		this.setState({
			showServerLineModal: true,
			menuShow: false
		})
	}
	cancelModal = () => {
		this.setState({
			showServerLineModal: false
		})
	}
	ShowClear = () => {
		this.injected.mainStore.clickClear = true;
		this.props.history.push('/main/search');
	}

	closeClear = () => {
		if (this.injected.mainStore.clickClear) {
			this.injected.mainStore.filterTxt = '';
			this.injected.mainStore.clickClear = false;
			this.props.history.push('/main/chat');
			this.injected.mainStore.changeTabName('chat')
		}
	}
	showAddGroupView = () => {
		this.closeClear();
		this.injected.mainStore.showAddGroupModal();
	}
	showSettings=()=>{
		this.injected.mainStore.showSettings();
	}
	

	submitTransmit(){

	}
	
	renderModelMessagesSend(){
		return (
			<>
				<Modal
				  bodyStyle={{"padding":0,"height":"400px"}}
					title="群发"
					destroyOnClose={true}
					width={700}
					onCancel={()=>{
						this.injected.mainStore.showSendMessagesModel(false)
					}}
					okText="发送"
					cancelText="取消"
					onOk={()=>{
						//this.submitTransmit();
						let ref = this.refMessages
						if(ref.current){
							if( this.state.sendingTransmit ){
								return;
							}
							(ref.current as any).submit()	;
							this.setState({
								sendingTransmit:true
							})
							setTimeout(()=>{
								this.setState({
									sendingTransmit:false
								})
							},500);
						}
					}}
					visible={this.injected.mainStore.sendMessagesModel.isShow }
				 
				 >
					<div style={{'overflow':'scroll',height:'100%'}}>
					
						<MesGroupSend visible={this.injected.mainStore.sendMessagesModel.isShow } submitTransmit={this.submitTransmit } ref={this.refMessages} onComplete={()=>{
							this.injected.mainStore.showSendMessagesModel(false)
						}}></MesGroupSend>
					</div>
					
				</Modal>
			</>
		)
	};
	renderModelSettings(){
		return (
			<>
				<Modal
				  bodyStyle={{"padding":0,"height":"500px"}}
					width={800}
					onCancel={()=>{
						this.injected.mainStore.showSettings(false)
					}}
					visible={this.injected.mainStore.settingsModal.isShow}
				 	footer={null}
				 >
					<MySetting></MySetting>
				</Modal>
			</>
		)
	}
	public render() {

		console.log(`${this.props.match.url}/test`);
		const sendList = (
			<>

				{systemStore.isNodesList.length > 0 ? (
					<div className="send-list" style={{ maxWidth: 'none' }}>
						<a onClick={this.showServerLineModal}>节点选择</a>
					</div>
				)
					: null
				}
				<div className="send-list" style={{ maxWidth: 'none' }}>
					<a onClick={this.loginOut}>退出登录</a>
				</div>
			</>
		);

		const ChatMainType = (
			<div className={this.state.isW3?"nav-box  w3":"nav-box"}>
				{ systemStore.env_name ? <div className="versionType">{ systemStore.env_name }</div>:null}
				<div className="dragbox"></div>
				<div className='main'>
					{/* <div onClick={this.goChatTest}>test</div> */}
					{/* <NavLink
						to={`${this.props.match.url}/my`}
						onClick={this.goMy }
						className="item"
					>
						<AvatorWithPhoto onlineStyle="icon" onlinestate={1} type={0} id={this.injected.systemStore.userId} size={50} classN="avator" />
					</NavLink> */}
					<Popover placement="rightTop" content={<MyInfoSimple />} visible={this.state.showMyInfo} trigger="click"
								onVisibleChange={()=>{
									this.setState({
										showMyInfo:!this.state.showMyInfo	
									})
								}}>
						<div
							//to={`${this.props.match.url}/messages`}
							//onClick={this.goMyInfo}
							className={`item ${this.injected.mainStore.tabName =='messages'?'selected':''}`}
							//activeClassName="selected"
						>
							
								{/* <Icon type="user" style={this.injected.mainStore.tabIndex == 2 ? selectedStyle : {}} /> */}
								<AvatorWithPhoto onlineStyle="icon" onlinestate={1} type={0} id={this.injected.systemStore.userId} size={46} classN="avator" />
							
							
						</div>
					</Popover>
	        
					
					<NavLink
						to={`${this.props.match.url}/chat`}
						onClick={() => this.goChart()}
						className="item"
						activeClassName="selected"
					>
						<Badge>
							{/* <Icon type="message" style={this.injected.mainStore.tabIndex == 0 ? selectedStyle : {}} /> */}
							{this.injected.mainStore.tabName == 'chat' ? (
								<SvgIcon name="message" size='18'></SvgIcon>
							) : (
								<SvgIcon name="message_no" size='18'></SvgIcon>
								)}
								
						</Badge>
						{ this.getUnreadCount()>0 ? <span className="unread-dot">{this.getUnreadCount()}</span>:null}
						
						<span className='label'>聊天</span>
					</NavLink>
					<NavLink
						to={`${this.props.match.url}/group`}
						onClick={() => this.goChart('group')}
						className="item"
						activeClassName="selected"
					>
						<Badge style={{ zIndex: 1 }}>
							{/* <Icon type="team" style={this.injected.mainStore.tabIndex == 1 ? selectedStyle : {}} /> */}
							{this.injected.mainStore.tabName == 'group' ? (
								<SvgIcon name="tongxunlu" size='18'></SvgIcon>
							) : (
								<SvgIcon name="tongxunlu_no" size='18'></SvgIcon>
								)}
							
						</Badge>
						{this.injected.requestStore.haveUnreadReq>0 ? <span className="unread-dot">{this.injected.requestStore.haveUnreadReq}</span>:null}
						<span className='label'>通讯录</span>
					</NavLink>
					<NavLink
						to={`${this.props.match.url}/team`}
						onClick={this.goTeam}
						className="item"
						activeClassName="selected"
					>
						{/* <Icon type="user" style={this.injected.mainStore.tabIndex == 2 ? selectedStyle : {}} /> */}
						{this.injected.mainStore.tabName == 'team' ? (
								<SvgIcon name="tuandui" size='20'></SvgIcon>
						) : (
							<SvgIcon name="tuandui_no" size='20'></SvgIcon>
							)}
							<span className='label'>团队</span>
					</NavLink>
					<div
						//to={`${this.props.match.url}/messages`}
						onClick={this.goSendMessages}
						className={`item ${this.injected.mainStore.tabName =='messages'?'selected':''}`}
						//activeClassName="selected"
					>
						{/* <Icon type="user" style={this.injected.mainStore.tabIndex == 2 ? selectedStyle : {}} /> */}
						{this.injected.mainStore.tabName == 'messages' ? (
							<SvgIcon name="qunfa" size='18'></SvgIcon>
						) : (
							<SvgIcon name="qunfa" size='18'></SvgIcon>
							)}
							<span className='label'>群发</span>
					</div>
					
					{
						// process.env.NODE_ENV == 'development'
						// 	? <NavLink to={`${this.props.match.url}/test`} >
						// 		<span style={{ lineHeight: '100%' }}>
						// 			TPage
						// 		</span>
						// 	</NavLink>
						// 	: null
					}
					{
						// systemStore.tabBarConfigList && systemStore.tabBarConfigList.tabBarImg && !isH5 ?
						// 	<NavLink
						// 	to={`${this.props.match.url}/3w`}
						// 	onClick={this.go3w}
						// 	className="item"
						// 	activeClassName="selected"
						// >
						// 	{this.injected.mainStore.tabIndex == 3 ? (
						// 		<img src={systemStore.tabBarConfigList.tabBarImg} alt="" />
						// 	) : (
						// 			<img src={systemStore.tabBarConfigList.tabBarImg1} alt="" />
						// 		)}
						// </NavLink> : null
					}
				</div>
				<div className='settings'>
					<div className='icon' onClick={this.goSetting}>
						<SvgIcon name="common-settings" size='18'></SvgIcon>
						<span>设置</span>
					</div>
				</div>
			</div>
		);
		// console.log(systemStore.tabBarConfigList,'当前状态',systemStore.tabBarConfigList.tabBarImg,ipcRender.isElectron)
		const isDobuleColumn = ()=>{
			const type = this.injected.mainStore.detailType;
			return type  == detailType.my || type == detailType.messages
		}
		return (
			<div className="main-wraper">
				<div className="main-wraper-dragbox"></div>
				{/* <div className="main-header">
					<div className="search-wraper">
						<Input
							suffix={
								this.injected.mainStore.clickClear ? <Icon type="close-circle" theme="filled" style={{ color: '#8CA6F5' }} onClick={this.closeClear} /> : null
							}
							onFocus={this.ShowClear}
							placeholder="搜索联系人、群组等"
							maxLength={30}
							prefix={<Icon type="search" style={{ color: '#8CA6F5' }} />}
							value={this.injected.mainStore.filterTxt}
							onChange={(e) => { this.injected.mainStore.changeFilterText(e.target.value); }}
						/>
					</div>
					<Tooltip title={tr(171)}> 
						<Icon type="user-add" style={{ color: '#D8E1FF', fontSize: '22px' }} onClick={() => this.injected.mainStore.showAddFriModal()} />
						 
					</Tooltip>
					<Tooltip title={tr(43)}> 
 						<Icon
							type="usergroup-add"
							style={{ color: '#D8E1FF', fontSize: '22px' }}
							onClick={this.showAddGroupView}
						/>
					</Tooltip>
					<span className="main-avator">
						<Popover
							placement="bottomLeft"
							title={this.injected.systemStore.nickname}
							content={sendList}
							trigger="click"
							visible={this.state.menuShow}
							onVisibleChange={this.handleSendType}
						>
							<AvatorWithPhoto type={0} id={this.injected.systemStore.userId} size={40} classN="head" />
							<Buttons className="click-me" type="primary">
								Click me
							</Buttons>
						</Popover>
					</span>
				</div> */}
				<Title />
				<div className={`main-body ${isDobuleColumn()?'main-body-full':''}`}>
					<div className="left-list" ref={ this.refLeftList }>
						<ResizeBar target={this.refLeftList} position='left' minSize={300}></ResizeBar>
						{ChatMainType}
						<div className="list-wraper">
						{this.getXmppStatus()}
							<Switch>
								<Route
									path={`${this.props.match.url}/chat`}
									component={ChartMessage}
									 
								/>
								
								<Route
									path={`${this.props.match.url}/group`}
									component={GroupView}
									 
								/>
								<Route
									path={`${this.props.match.url}/team`}
									component={TeamView}
									 
								/>
								<Route
									path={`${this.props.match.url}/my`}
									component={()=><div></div>}
									 
								/>
								<Route
									path={`${this.props.match.url}/CrtGroup`}
									component={MySetting} 
								/>
								<Route
									path={`${this.props.match.url}/search`}
									component={Search} 
								/>
								<Route 
									path={`${this.props.match.url}/settings`} 
									component={MySetting}
								/>
								{
									// process.env.NODE_ENV == 'development'
									// 	? <Route
									// 		path={`${this.props.match.url}/test`}
									// 		component={Update}
									// 		style={{ WebkitUserDrag: 'none' }}
									// 	/>
									// 	: null
								}
								<Redirect
									exact
									from={`${this.props.match.url}/`}
									to={`${this.props.match.url}/chat`}
								/>
							</Switch>
						</div>
						
					</div>
					<div
						className={`right-content ${!this.injected.mainStore.detailType ||
							this.injected.mainStore.detailType == detailType.none
							|| (this.injected.mainStore.detailType == detailType.message &&
								!this.injected.chatStore.currentChatData.name)
							? 'hide'
							: ''}`}
						onClick={this.closeClear}
					>
						<Route path={`${this.props.match.url}/`} component={RightContent} />
					</div>
				</div>
				
				{ this.renderModelSettings() }
				{ this.renderModelMessagesSend()}
				<Modal
					visible={this.injected.mainStore.addFriModalData.isShow}
					mask={false}
					centered
					title="添加好友/企业"
					destroyOnClose={true}
					width={420}
					footer={null}
					onCancel={()=>{
						this.setState({
							keyword:''
						})
						this.injected.mainStore.closeAddFriModal()
					}}
				>
					<div className="addfriend-box">
						{/** 这边重复定义时有原因的,dialog 层级有点问题 */}
						<UserSearch></UserSearch>
						{/* <div className="search-wraper">
							<input
								type="text"
								placeholder="请输入手机号/ID号/公司名称"
								onChange={this.handleMobileChange}
								value={this.state.keyword}
								maxLength={30}
							/>
							<Button onClick={() => this.injected.mainStore.searchUserFun(this.state.keyword)}>
								搜索
							</Button>
						</div> */}
						<div className="search-user-wraper">
							{Array.isArray(this.injected.mainStore.searchUserList) &&
								this.injected.mainStore.searchUserList.length > 0 ? (
									this.injected.mainStore.searchUserList.map((item, index) => {
										return (
											<div key={index} className="user-item">
												<span>
													<span>昵称：{item.name}</span>
													<span style={{marginLeft:'5px'}}>ID: {item.id}</span>
												</span>
												<span>
													<Icon
														type="user-add"
														style={{ fontSize: '20px' }}
														onClick={() => this.addFriend(item)}
													/> 
												</span>
											</div>
										);
									})
								) : (
									<span className="no-data">暂无搜索用户</span>
								)}
						</div>
					</div>
				</Modal>
				
				{this.injected.mainStore.infoUserId&& this.injected.mainStore.infoUserId!=='10005'? (
					<UserInfomodal userId={this.injected.mainStore.infoUserId} />
				) : null}
				{this.state.showServerLineModal ? (
					<ServerLineSelectModal needChangeConect serverList={systemStore.isNodesList} cancelModal={this.cancelModal} />
				) : null}
			</div>
		);
	}
}
